const app = getApp()
import http from '../../utils/request.js'
import api from '../../utils/api.js'
let util = require("../../utils/util.js")
Page({
  data: {
    tabs: [{
      name: '击杀',
      key: 'kills'
    }, {
      name: '死亡',
      key: 'deaths'
    }, {
      name: '送一血',
      key: 'firstBloodGiven'
    }, {
      name: '拿一血',
      key: 'firstBloodClaimed'
    }, {
      name: '控制',
      key: 'stuns'
    }, {
      name: '堆野',
      key: 'creepsStacked'
    }, {
      name: 'gpm',
      key: 'gpm'
    }, {
      name: 'xpm',
      key: 'xpm'
    }, {
      name: '正补',
      key: 'lastHitCount'
    }, {
      name: '反补',
      key: 'denyCount'
    }, {
      name: '治疗',
      key: 'healing'
    }, {
      name: '塔伤害',
      key: 'towerDamage'
    }],
    tabCur: 0,
    scrollLeft: 0,
    totalArray: [],
    totalsState: 'close',
    heroes: [],
    heroPage: 1,
    yearMonth: '',
    maxHeroOpen: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let {
      month
    } = options
    let date;
    let url
    if (month) {
      date = new Date(month)
      url = api.report + '?yearMonth=' + month
    } else {
      date = new Date()
      url = api.currentReport
      month = date.getFullYear()
      let m = date.getMonth() + 1
      if (m < 10) {
        m = '0' + m
      }
      month = month + '-' + m
    }
    this.setData({
      yearMonth: month
    })

    let title = '我们这个局 ' + date.getFullYear() + '年' + (date.getMonth() + 1) + '月 月报'
    wx.setNavigationBarTitle({
      title: title
    })
    http.get(url)
      .then(result => {
        let data = result.data.data;
        this.setData(data)
        let maxWin = {
          winRate: 0
        };
        let minWin = {
          winRate: 100
        }
        let playerCount = 0;
        for (let player in data.totals) {
          playerCount++
          let total = data.totals[player]
          if (total.totalMatches < data.count >> 3) {
            continue
          }
          let winRate = total.wins / total.totalMatches * 100
          winRate = winRate.toFixed(2)
          // console.log(data.playerMap[player].name, total.totalMatches, winRate)
          if (winRate > maxWin.winRate) {
            maxWin.wins = total.wins
            maxWin.player = player
            maxWin.winRate = winRate
            maxWin.count = total.totalMatches
          }
          if (winRate < minWin.winRate) {
            minWin.wins = total.wins
            minWin.player = player
            minWin.winRate = winRate
            minWin.count = total.totalMatches
          }
        }
        let maxHeros = {
          avg: 0
        }
        let minHeros = {
          avg: 99
        }

        for (let id in data.playerHeroMap) {
          let heros = data.playerHeroMap[id]
          let player = data.playerMap[id]
          let total = data.totals[player.id]
          if (total.totalMatches < data.count >> 1) {
            continue
          }
          let avg = heros.length / total.totalMatches
          if (avg > maxHeros.avg || (avg == maxHeros.avg && heros.length > maxHeros.data)) {
            maxHeros.player = player
            maxHeros.heros = heros
            maxHeros.data = heros.length
            maxHeros.avg = avg
            maxHeros.count = total.totalMatches
          }
          if (avg < minHeros.avg) {
            minHeros.player = player
            minHeros.heros = heros
            minHeros.data = heros.length
            minHeros.count = total.totalMatches
            minHeros.avg = avg
          }
        }
        this.setData({
          maxWin: {
            wins: maxWin.wins,
            count: maxWin.count,
            winRate: maxWin.winRate,
            player: data.playerMap[maxWin.player],
          },
          minWin: {
            wins: minWin.wins,
            count: minWin.count,
            winRate: minWin.winRate,
            player: data.playerMap[minWin.player],
          },
          maxHeros,
          minHeros,
          playerCount
        })
        setTimeout(() => {
          let totalArray = []
          for (let i = 0; i < this.data.tabs.length; i++) {
            totalArray.push(this.loadTotalData(i))
          }
          this.setData({
            totalArray
          })
        }, 10)
      })
    this.loadHeroes()
  },
  change(e) {
    let index = e.detail.current
    this.setData({
      tabCur: index,
      scrollLeft: (index - 1) * 60
    })
  },
  tabSelect(e) {
    let index = e.currentTarget.dataset.id
    this.setData({
      tabCur: index,
      scrollLeft: (index - 1) * 60
    })
  },
  loadTotalData(index) {
    let selected = this.data.tabs[index]
    let arr = []
    for (let id in this.data.totals) {
      let total = this.data.totals[id]
      let data = parseFloat((total[selected.key]).toFixed(2))
      let avg = parseFloat((data / total.totalMatches).toFixed(2))
      if (selected.key === 'gpm' || selected.key === 'xpm') {
        data = ''
      }
      if (selected.key === 'firstBloodGiven' || selected.key === 'firstBloodClaimed') {
        avg = ''
      }
      arr.push({
        player: this.data.playerMap[id],
        data,
        count: total.totalMatches,
        avg
      })
      arr.sort((o1, o2) => {
        if (o1.data) {
          return o2.data - o1.data
        }
        return o2.avg - o1.avg
      })
    }
    return arr
  },
  showMore() {
    this.setData({
      totalsHeight: this.data.playerCount * 110,
      'totalsState': 'open'
    })
  },
  hideMore() {
    let count = this.data.playerCount
    if (count > 5) {
      count = 5
    }
    this.setData({
      totalsHeight: count * 110,
      'totalsState': 'close'
    })
  },
  openMaxHero() {
    this.setData({
      maxHeroOpen: true
    })
  },
  closeMaxHero() {
    this.setData({
      maxHeroOpen: false
    })
  },
  loadHeroes() {
    http.get(api.monthHeroes, {
        size: 5,
        current: this.data.heroPage,
        yearMonth: this.data.yearMonth
      })
      .then(result => {
        let list = result.data.data.records;
        list = this.data.heroes.concat(list)
        this.setData({
          heroes: list
        })
      });
  },
  naviPlayer(e) {
    let accountid = e.target.dataset.accountid
    wx.navigateTo({
      url: `/pages/Player/Player?id=${accountid}`,
    })
  },
  moreHero() {
    this.setData({
      heroPage: this.data.heroPage + 1
    })
    this.loadHeroes()
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },
  onShareAppMessage: function() {

  },
  onPageScroll(e) {
    if (e.scrollTop > 100) {
      this.setData({
        floorstatus: true
      });
    } else {
      this.setData({
        floorstatus: false
      });
    }
  },
  //回到顶部
  goTop: function(e) { // 一键回到顶部
    if (wx.pageScrollTo) {
      wx.pageScrollTo({
        scrollTop: 0
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
      })
    }
  }
})